<template>
<!-- <div class="" v-loading="loading"
    element-loading-spinner="el-icon-loading"
    element-loading-background="rgba(255, 255, 255 0.8)"> -->
<div class="" style="min-height: 500px;" v-loading="loading">
  <div class="va-container" id="vipapp" v-if="(!row || isMoidfy)" v-show="!loading">
    <div class="flex-row vip-prompt">
      <p class="prompt-text">团体会员请在“陕西省地理信息产业协会综合业务系统”中依据实际情况填写此申请表内容； 并将填写完毕的申请表文档打印成纸质版，经由负责人签字盖章后，将纸质版扫描件以附件的形式上传至综合业务系统； 请确保在综合业务系统中填写的信息与扫描件信息一致。
      </p>
      <el-button type="success" icon="el-icon-download" style="font-size: 14px;padding: 8px;" @click="downloadFile()">会员申请表</el-button>

      <!-- 暂时隐藏 -->
      <!-- <div class="flex-row">
          <el-button type="success" icon="el-icon-download">下载Excel模板</el-button>
          <el-button type="success" icon="el-icon-edit-outline">导入信息</el-button>
        </div> -->
    </div>
    <time-line>
      <el-collapse v-model="activeName" accordion>
        <timeline-item :color="activeName === '1' ? 'green' : '#BAC1B0'">
          <el-collapse-item title="会员单位基本信息" name="1">
            <template slot="title">会员单位基本信息&nbsp;&nbsp;&nbsp;<i class="header-icon el-icon-edit" v-show="activeName !== '1'"></i></template>
            <vipunit-info :data.sync="unitinfo" ref="unitinfo" @vali-reec="setIsSave"></vipunit-info>
          </el-collapse-item>
        </timeline-item>
        <timeline-item :color="activeName === '2' ? 'green' : '#BAC1B0'">
          <el-collapse-item title="会员类型及代表人信息" name="2">
            <template slot="title">会员类型及代表人信息&nbsp;&nbsp;&nbsp;<i class="header-icon el-icon-edit" v-show="activeName !== '2'"></i></template>
            <type-info :data.sync="typeinfo" ref="typeinfo"></type-info>
          </el-collapse-item>
        </timeline-item>
        <timeline-item :color="activeName === '3' ? 'green' : '#BAC1B0'" v-if="typeinfo.memberType === 'TEAM'">
          <el-collapse-item title="会员单位联系人" name="3">
            <template slot="title">会员单位联系人&nbsp;&nbsp;&nbsp;<i class="header-icon el-icon-edit" v-show="activeName !== '3'"></i></template>
            <vipunit-contacts :data.sync="unitcon" ref="unitcon"></vipunit-contacts>
          </el-collapse-item>
        </timeline-item>
        <timeline-item :color="activeName === '4' ? 'green' : '#BAC1B0'" v-if="typeinfo.memberType === 'TEAM'">
          <el-collapse-item title="理事会职务申请信息" name="4">
            <template slot="title">理事会职务申请信息&nbsp;&nbsp;&nbsp;<i class="header-icon el-icon-edit" v-show="activeName !== '4'"></i></template>
            <counciljob-app :data.sync="coujob" ref="coujob"></counciljob-app>
          </el-collapse-item>
        </timeline-item>
        <timeline-item :color="activeName === '5' ? 'green' : '#BAC1B0'" v-if="typeinfo.memberType === 'TEAM'">
          <el-collapse-item title="会员单位其他信息" name="5">
            <template slot="title">会员单位其他信息&nbsp;&nbsp;&nbsp;<i class="header-icon el-icon-edit" v-show="activeName !== '5'"></i></template>
            <vipunit-other-info :data.sync="otherinfo" ref="otherinfo" @priview="priview" @comfirm="comfirm"></vipunit-other-info>
          </el-collapse-item>
        </timeline-item>
        <timeline-item :color="activeName === '6' ? 'green' : '#BAC1B0'" v-if="typeinfo.memberType === 'PERSONAL'">
          <el-collapse-item title="个人其他信息" name="6">
            <template slot="title">个人其他信息&nbsp;&nbsp;&nbsp;<i class="header-icon el-icon-edit" v-show="activeName !== '6'"></i></template>
            <person-other-info :data.sync="personotherinfo" ref="personotherinfo" @priview="priview" @comfirm="comfirm"></person-other-info>
          </el-collapse-item>
        </timeline-item>
      </el-collapse>
    </time-line>
    <div class="tc">
      <el-button type="success width-100" plain round @click="priview()">预览</el-button>
      <el-button type="success width-200" round @click="comfirm()">提交申请</el-button>
    </div>
  </div>

  <div class="va-container flex-column-center promp-msg" v-if="row && row.verifyStatus === 'WAIT' && !isMoidfy">
    <img src="../assets/shenhezhong.jpg" alt="">
    <p>提交成功，需要三个工作日，请等待。。。</p>
    <el-button type="success" round @click="previewResult()">查看申请表</el-button>
    <!-- <el-button type="success" round @click="modify()">重新编辑</el-button> -->
  </div>
  <div class="va-container flex-column-center promp-msg" v-if="row && row.verifyStatus === 'SUCCESS' && !isMoidfy">
    <img src="../assets/shenhetongguo.jpg" alt="">
    <p>恭喜您！审核已经通过，成为我们的会员了</p>
    <el-button type="success" round @click="previewResult()">查看申请表</el-button>
  </div>
  <div class="va-container flex-column-center promp-msg" v-if="row && row.verifyStatus === 'FAIL' && !isMoidfy">
    <img src="../assets/shenheshibai.jpg" alt="">
    <p>很抱歉！您的申请未能通过！</p>
    <p>原因：{{row.reason}}</p>
    <el-button type="success" round @click="modify()">重新编辑</el-button>
  </div>
</div>
</template>

<script>
import $ from 'jquery'
import axios from 'axios'
import TypeInfo from './vipform/TypeInfo'
import VipunitInfo from './vipform/VipunitInfo'
import VipunitContacts from './vipform/VipunitContacts'
import CounciljobApp from './vipform/CounciljobApp'
import VipunitOtherInfo from './vipform/VipunitOtherInfo'
import PersonOtherInfo from './vipform/PersonOtherInfo'

let v = async function(self, noAnnex) { // 第二个参数为附件是否为必须，在下载模板时，附件不为必须,默认不传，为false
  let result1 = await self.$refs.unitinfo.validate()
  if (!result1) {
    self.activeName = '1'
    return false
  }
  let result2 = await self.$refs.typeinfo.validate()
  if (!result2) {
    self.activeName = '2'
    return false
  }
  if (self.typeinfo.memberType === 'TEAM') {
    let result3 = await self.$refs.unitcon.validate()
    if (!result3) {
      self.activeName = '3'
      return false
    }
  }

  if (self.typeinfo.memberType === 'TEAM') {
    let result4 = await self.$refs.coujob.validate()
    if (!result4) {
      self.activeName = '4'
      return false
    }
  }

  if (self.typeinfo.memberType === 'TEAM') {
    let result5 = await self.$refs.otherinfo.validate()
    if (!result5) {
      self.activeName = '5'
      return false
    }
  }

  if ( (!noAnnex && (self.otherinfo.attachment.length === 0 || self.otherinfo.license.length === 0))) {
    if (self.otherinfo.attachment.length === 0) {
      self.$message({
        message: '请上传会员申请盖章附件',
        type: 'warning'
      })
    }
    if (self.otherinfo.license.length === 0) {
      self.$message({
        message: '请上传加盖企业公章营业执照附件',
        type: 'warning'
      })
    }
    self.activeName = '5'
    return false
  }
  return true
}
export default {
  components: {
    TypeInfo,
    VipunitInfo,
    VipunitContacts,
    CounciljobApp,
    VipunitOtherInfo,
    PersonOtherInfo
  },
  title: '会员申请',
  name: 'vip-app',
  data() {
    return {
      isSave: true, // 是否可以保存
      activeName: '1',
      isMoidfy: false,
      loading: true,
      typeinfo: {
        memberType: "TEAM",
        gisMember: "YES",
        username: '',
        sex: '1',
        birthday: '',
        phone: '',
        fixedTelephone: '',
        email: '',
        professionalTitle: '',
        position: '',
        politicalBackground: ''
      },
      unitcon: {
        companyPrincipalName: '',
        fax: '',
        contactsName: '',
        contactsPhone: '',
        contactsFixedTelephone: '',
        contactsPosition: '',
        contactsProfessionalTitle: '',
        contactsWechat: '',
        contactsQq: '',
        contactsEmail: ''
      },
      unitinfo: {
        companyName: '',
        organizationCode: '',
        companyAddress: '',
        companyPost: '',
        companyNature: '',
        grade: '',
        provinceCode: '',
        cityCode: '',
        areaCode: '',
        cityName: ''
      },
      otherinfo: {
        companyIntroduce: '',
        companyOpinion: '',
        companyPrincipalName: '',
        attachment: [],
        license: []
      },
      coujob: {
        councilPosition: 'N',
        workExperience: '',
        educationalBackground: ''
      },
      personotherinfo: {
        personalResume: '',
        attachment: []
      },
      row: null
    }
  },
  mounted() {
    this.getPersonApp()
  },
  methods: {
    priview() {
      if (this.typeinfo.memberType === 'PERSONAL') {
        const {
          href
        } = this.$router.resolve({
          name: 'VipPreview',
          query: Object.assign({}, this.typeinfo, this.unitcon, this.unitinfo, this.personotherinfo, this.coujob)
        })
        window.open(href, '_blank')
      } else {
        const {
          href
        } = this.$router.resolve({
          name: 'VipPreview',
          query: Object.assign({}, this.typeinfo, this.unitcon, this.unitinfo, this.otherinfo, this.coujob)
        })
        window.open(href, '_blank')
      }

      // window.open(this.$router)
      // this.$router.push({name: 'VipPreview',
      // params: Object.assign({}, this.typeinfo, this.unitcon, this.unitinfo, this.otherinfo, this.coujob)})
    },
    previewResult() {
      // this.$router.push({name: 'VipPreview', params: this.row})
      const {
        href
      } = this.$router.resolve({
        name: 'VipPreview',
        query: this.row
      })
      window.open(href, '_blank')
    },
    comfirm() {
      if (!this.isSave) {
        this.$confirm('该企业已是会员单位，不可重复申请，请用企业账号登录')
        return
      }


      let that = this
      // 校验
      v(this).then(result => {
        if (result) {
          // let obj
          // 取消会员类型分类
          // if (that.typeinfo.memberType === 'PERSONAL') {
          //   obj = Object.assign({}, that.typeinfo, that.unitinfo, that.personotherinfo)
          // } else {
          //   obj = Object.assign({}, that.typeinfo, that.unitcon, that.unitinfo, that.otherinfo, that.coujob)
          // }
          let obj = Object.assign({}, this.row, that.typeinfo, that.unitcon, that.unitinfo, that.otherinfo, that.coujob)
          // 上传会员申请盖章附件,上传加盖企业公章营业执照附件
          if (typeof obj.attachment === 'object' && typeof obj.license === 'object') {
            obj.attachment = JSON.stringify([
              ...obj.attachment.map(item => {
                item.type = 'attachment'
                return item
              }),
              ...obj.license.map(item => {
                item.type = 'license'
                return item
              })
            ])
          }
          // 其他信息附件
          if (obj.attachment.length === 0) {
            obj.attachment = null
          } else {
            if (typeof obj.attachment === 'object') {
              obj.attachment = JSON.stringify(obj.attachment)
            }
          }
          // obj.userId  = getuser().data.user.userId
          obj.userId = that.$store.state.user.user.user.userId
          obj.saveSubmit = 'SUBMIT'

          this.loading = true
          axios.post('/mscs/member/addUserMemberInfo', obj).then((res) => {
            if (res.data.code === 1) {
              that.isMoidfy = false
              that.row = obj
              that.row.verifyStatus = 'WAIT'
            } else {
              this.$message({
                showClose: true,
                message: res.data.data[0].errorMsg,
                type: 'error'
              })
            }
          }).catch((error) => {
            this.$catchError(error)
          }).finally(() => {
            this.loading = false
          })
        }
      })
    },
    getPersonApp() {
      axios.post('/mscs/member/findMemberByUserid', this.$paramsConvert({
        userId: this.$store.state.user.user.user.userId
      })).then((res) => {
        if (res.data.code === 1) {
          this.row = res.data.data
        }
      }).catch((error) => {
        this.$catchError(error)
      }).finally(() => {
        this.loading = false
      })
    },
    modify() {
      this.typeinfo.memberType = this.row.memberType
      this.typeinfo.gisMember = this.row.gisMember
      this.typeinfo.username = this.row.username
      this.typeinfo.sex = `${this.row.sex}`
      this.typeinfo.birthday = this.$formatYMD(this.row.birthday)
      this.typeinfo.phone = this.row.phone
      this.typeinfo.fixedTelephone = this.row.fixedTelephone
      this.typeinfo.email = this.row.email
      this.typeinfo.professionalTitle = this.row.professionalTitle
      this.typeinfo.position = this.row.position
      this.typeinfo.politicalBackground = this.row.politicalBackground

      this.unitinfo.companyName = this.row.companyName
      this.unitinfo.organizationCode = this.row.organizationCode
      this.unitinfo.companyAddress = this.row.companyAddress
      this.unitinfo.companyPost = this.row.companyPost
      this.unitinfo.companyNature = this.row.companyNature
      this.unitinfo.grade = this.row.grade
      this.unitinfo.provinceCode = this.row.provinceCode
      this.unitinfo.cityCode = this.row.cityCode
      this.unitinfo.areaCode = this.row.areaCode
      this.unitinfo.cityName = this.row.cityName

      this.unitcon.contactsName = this.row.contactsName ? this.row.contactsName : ''
      this.unitcon.companyPrincipalName = this.row.companyPrincipalName ? this.row.companyPrincipalName : ''
      this.unitcon.fax = this.row.fax ? this.row.fax : ''
      this.unitcon.contactsPhone = this.row.contactsPhone ? this.row.contactsPhone : ''
      this.unitcon.contactsFixedTelephone = this.row.contactsFixedTelephone ? this.row.contactsFixedTelephone : ''
      this.unitcon.contactsPosition = this.row.contactsPosition ? this.row.contactsPosition : ''
      this.unitcon.contactsProfessionalTitle = this.row.contactsProfessionalTitle ? this.row.contactsProfessionalTitle : ''
      this.unitcon.contactsWechat = this.row.contactsWechat ? this.row.contactsWechat : ''
      this.unitcon.contactsQq = this.row.contactsQq ? this.row.contactsQq : ''
      this.unitcon.contactsEmail = this.row.contactsEmail ? this.row.contactsEmail : ''

      this.otherinfo.companyIntroduce = this.row.companyIntroduce ? this.row.companyIntroduce : ''
      this.otherinfo.companyOpinion = this.row.companyOpinion ? this.row.companyOpinion : ''
      this.otherinfo.companyPrincipalName = this.row.companyPrincipalName ? this.row.companyPrincipalName : ''
      this.otherinfo.attachment = this.row.attachment ? this.row.attachment : ''

      this.coujob.councilPosition = this.row.councilPosition ? this.row.councilPosition : 'N'
      this.coujob.workExperience = this.row.workExperience ? this.row.workExperience : ''
      this.coujob.educationalBackground = this.row.educationalBackground ? this.row.educationalBackground : ''

      this.personotherinfo.personalResume = this.row.personalResume ? this.row.personalResume : ''
      this.personotherinfo.attachment = this.row.attachment ? this.row.attachment : ''

      this.isMoidfy = true
    },
    setIsSave(info) {
      if (info) {
        this.isSave = false
        this.$confirm('该企业已是会员单位，不可重复申请，请用企业账号登录')
      } else {
        this.isSave = true
      }
    },
    downloadFile() {
      v(this, true).then(result => {
        if (result) {
          let obj = Object.assign({}, this.row, this.typeinfo, this.unitcon, this.unitinfo, this.otherinfo, this.coujob)
          let params = {
            filePath: 'http://cdn.i-tudou.com/document/member-applay.xlsx',
            member: JSON.stringify(obj)
          }
          axios.post('mscs/member/exportMemberExcel', this.$paramsConvert(params),{responseType: 'arraybuffer'}).then(res => {
            const content = res.data
            const blob = new Blob([content], {type: "application/vnd.ms-excel"})
            const fileName = '会员申请表.xlsx'
            if ('download' in document.createElement('a')) { // 非IE下载
              const elink = document.createElement('a')
              elink.download = fileName
              elink.style.display = 'none'
              elink.href = URL.createObjectURL(blob)
              document.body.appendChild(elink)
              elink.click()
              URL.revokeObjectURL(elink.href) // 释放URL 对象
              document.body.removeChild(elink)
              // let objectUrl = URL.createObjectURL(blob)
              // window.location.href = objectUrl
            } else { // IE10+下载
              navigator.msSaveBlob(blob, fileName)
            }
          }).catch(error => {
            this.$catchError(error)
          })

        }
      })

    }
  },
  watch: {
    '$store.state.user.token' (val) {
      if (val) {
        this.getPersonApp()
      }
    }
  }
}
</script>
<style>
/* 顶部提示文字 */

.vip-prompt {
  margin-top: -20px;
  margin-bottom: 20px;
}

.vip-prompt p {
  margin: 0;
  line-height: 20px;
  margin-right: 20px;
}

.va-container {
  padding-top: 60px;
}

.va-container .el-collapse-item__header {
  font-size: 18px;
  color: #3b541c;
  height: auto;
  line-height: normal;
  border-bottom: none;
}

/* 去掉展开和默认的底部边框 */

.va-container .el-collapse {
  border: none;
}

.va-container .el-collapse-item__wrap {
  border-bottom: none;
}

/* 一下两个是让标识圈偏离整体文档 */

.va-container .timeline {
  margin-left: -50px;
}

.va-container .timeline-item-content {
  padding-left: 50px;
}

/* 清除右边展开的标识箭头 */

.va-container .el-collapse-item__arrow:before {
  content: "";
}

/* 让标题文字和右边图标对其 */

.va-container .el-collapse-item:last-child {
  margin-top: -2px;
}

/* 修改展开想的title */

.va-container .is-active {
  font-size: 20px;
  color: #3b541c;
}

.va-container .el-icon-edit:before {
  background: #94C05A;
  border-radius: 50%;
  color: #FFFFFF;
  padding: 3px;
  font-size: 15px;
}
/* 去掉折叠下方的间距，防止表单出现滚动 */

#vipapp .el-collapse-item__content {
  padding-bottom: 0;
}
</style>
